package main

import (
	logging "github.com/sirupsen/logrus"
	"io"
	"net"
	"time"
	"webdemo/src/zinx/znet"
)

// 模拟客户端
func main() {
	conn, err := net.Dial("tcp", "127.0.0.1:8999")
	if err != nil {
		logging.Error("Client net.Dial err is ", err)
		return
	}
	logging.Info("Client net.Dial success ")

	for true {
		// 发送封包消息
		dp := znet.NewDataPack()
		binaryMsg, err := dp.Pack(znet.NewMsgPackage(0, []byte("client msg...")))
		if err != nil {
			logging.Error("Client dp.Pack err is ", err)
			continue
		}
		_, err = conn.Write(binaryMsg)
		if err != nil {
			logging.Error("Client conn.Write err is ", err)
			continue
		}
		// 读取服务器回复的消息
		binaryHead := make([]byte, dp.GetHeadLen())
		_, err = io.ReadFull(conn, binaryHead)
		if err != nil {
			logging.Error("Client io.ReadFull err is ", err)
			return
		}
		msgHead, err := dp.Unpack(binaryHead)
		if err != nil {
			logging.Error("Client dp.Unpack err is ", err)
			return
		}
		if msgHead.GetDataLen() > 0 {
			msg := msgHead.(*znet.Message)
			msg.Data = make([]byte, msg.GetDataLen())
			_, err = io.ReadFull(conn, msg.Data)
			if err != nil {
				logging.Error("Client io.ReadFull err is ", err)
				return
			}
			logging.Info("Client receive msg is ", string(msg.Data))

		}
		time.Sleep(time.Second * 5)
	}
}
